# configuration for this webapp

import tsnakelets.testcookie
import tsnakelets.test
import tsnakelets.form
import tsnakelets.snoop

from snakeserver.plugin import ServerPlugin, RequestPlugin, ErrorpagePlugin, SEQUENCE_NORMAL, SEQUENCE_LATE
from snakeserver.user import LoginUser

def dirListAllower(path):
	return True	# for test purposes: allow all paths (including snakelet source directory)
def documentAllower(path):
	return True # for test purposes: allow all documents (including Python source files)

name="Test Web application"
docroot="."
assetLocation="img"
sessionTimeoutSecs=20
sessionTimeoutPage="timeout.html"

# indexPages = ["index.y", "index.html", "index.htm"]
#defaultOutputEncoding="UTF-8"
#defaultContentType="text/html"

# defaultErrorPage="errorpage.y"   # set a global error page


snakelets= {
	"cookie.sn": tsnakelets.testcookie.TestCookie,
	"snoop.sn": tsnakelets.snoop.Snoop,
	"memory.sn": tsnakelets.test.Memory,
	"redirect.sn": tsnakelets.test.Redirecter,
	"encoding.sn": tsnakelets.test.Encoding,
	"error.sn": tsnakelets.test.Error,
	"included.sn": tsnakelets.test.Included,
	"utf8form/formaccepter.sn": tsnakelets.form.FormAccepter,
	"utf8form/utf8formaccepter.sn": tsnakelets.form.UTF8FormAccepter,
	"auth/mgmt/httpauth.sn": tsnakelets.test.HTTPAuthenticator_management,
	"auth/bo/httpauth.sn": tsnakelets.test.HTTPAuthenticator_backoffice,
	"doc/*.pdf": tsnakelets.snoop.Snoop,
	"fake/index.sn": tsnakelets.test.FakeIndex,    # fake index page 
	"index.sn": tsnakelets.test.FakeIndex,      # fake index page in webapp root
	}

configItems = {
	"maxPOSTsize":  400000,
	}

authorizationPatterns={
    "authpattern.y": ["admin"],
    "tstauth/*": ["admin"]
 }


def authorizeUser(authmethod, url, username, password, request):
    #  hard-coded users with their passwords and roles
    passwords = { "mike": "apples",   "janet": "pookie" }       # usually the pw's would be encrypted or hashed
    privileges = { "mike": ["admin","dba"],  "janet": ["secretary"] }
    if username in passwords and passwords[username]==password:
        # as an example, we return a full LoginUser object:
        return LoginUser(username,password,"Full username here",privileges[username])
        # ...but it is also possible to just return the set of privileges:
        # return privileges[username] 
    else:
        return None

class TestServerPlugin(ServerPlugin):
    PLUGIN_SEQ=SEQUENCE_LATE
    def plug_init(self,server):
        print "Test Plugin: init"
    def plug_serverStart(self, server):
        print "Test Plugin: serverStart"
    def plug_serverStop(self, server):
        print "Test Plugin: serverStop"
    def plug_sessionCreated(self, webapp, session, request):
        print "Test Plugin: session created: 0x%08x" % id(session)
    def plug_sessionDestroyed(self, webapp, session, request):
        print "Test Plugin: session destroyed: 0x%08x" % id(session)

class TestRequestPlugin(RequestPlugin):
    PLUGIN_SEQ=SEQUENCE_LATE
    def plug_requestExecute(self, webapp, snakelet, request, response):
        print "Test plugin: requestExecute"
        return False
    def plug_requestFinished(self, webapp, snakelet, request, response, outputarray=[None]):
        print "Test plugin: requestFinished"
        return False

class TestErrorpagePlugin(ErrorpagePlugin):
    PLUGIN_NAME = "CustomErrorPage"
    def plug_serverErrorpage(self, path, code, message, explainTxt, outputStream):
        # show that it is possible to intercept server error pages.
        outputStream.write("""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Custom server error page</title></head>
<body style="background-color: #400030; color: #ffff80">
<h2>There was a problem in the server.</h2>
<p>
<em>That's why you see this custom server error page ;-)</em>
<h3>URL &quot;%(path)s&quot; caused the error:</h3>
<table border="1" cellspacing="3">
<tr><td>status code</td><td>%(code)d</td></tr>
<tr><td>message</td><td>%(message)s</td></tr>
<tr><td>explanation</td><td>%(explainTxt)s</td></tr>
</table>
<hr>
<address>This page is defined in the Errorpage plugin, which is set in the 'test' webapp init code</address>
</body></html>""" % vars() )
        return True # custom error page output.
     
       
def init(webapp):
    print ">> INIT WEBAPP",webapp
    try:
        webapp.addPlugin( TestServerPlugin() )
        webapp.addPlugin( TestRequestPlugin() )
        webapp.addPlugin( TestErrorpagePlugin() )
    except ValueError:
        # plugins can only be registered once, but this code is executed for every vhost
        pass
    # try to use the page cache plugin to register a page to cache:
    try:
        webapp.server.getPlugin("PageCacher").addCacheURL("/test/test.y", 10)
        print "PageCacher plugin found, /test/test.y will be cached with 10-second timeouts."
    except KeyError:
        print "PageCacher plugin not found."
    # print 1/0 # XXX for mgmt test purposes
    
def close(webapp):
    print ">> CLOSE DOWN WEBAPP",webapp
